package com.cn.lf.wx.dacs.bussiness.author.utils;

import java.util.Date;
import java.util.Map;

import com.cn.ym.log.Log;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class JwtUtils {
    //盐值
    private static String key = "asd121245h21lk3j45h1345hjk425r6543l5";

    private static long ttl = Constant.TimeValue.DAY * 1000;//24个小时

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public long getTtl() {
        return ttl;
    }

    public void setTtl(long ttl) {
        this.ttl = ttl;
    }

    /**
     * @param claims 载荷内容
     * @param ttl    有效时长
     * @return
     */
    public static String createToken(Map<String, Object> claims, long ttl) {
        JwtUtils.ttl = ttl * 1000;
        return createToken(claims);
    }


    /**
     * @param claims 载荷
     * @return token
     */
    public static String createToken(Map<String, Object> claims) {

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        JwtBuilder builder = Jwts.builder()
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256, key);

        if (claims != null) {
            builder.setClaims(claims);
        }

        if (ttl > 0) {
            Date date = new Date(nowMillis + ttl);
            Log.info("token 失效时间 {}"+date);
            builder.setExpiration(date);
        }
        return builder.compact();
    }

    public static Claims parseJWT(String jwtStr) throws Exception {
        Claims body;
        try {
            body = Jwts.parser()
                    .setSigningKey(key)
                    .parseClaimsJws(jwtStr)
                    .getBody();
        } catch (Exception exception) {
            throw new Exception(exception.getMessage());
        }
        return body;
    }
}
